package com.seleniti.enpareja.web.desktop.client.ui.widget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.seleniti.enpareja.web.desktop.client.ui.resources.CommonResources;

public class FloatingTipWidget extends Composite {

	private static TemplateUiBinder uiBinder = GWT.create(TemplateUiBinder.class);

	interface TemplateUiBinder extends UiBinder<Widget, FloatingTipWidget> {
	}

	public enum Align {
		TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT;
	}

	@UiField
	Image topLeft;

	@UiField
	Image topRight;

	@UiField
	Image bottomLeft;

	@UiField
	Image bottomRight;

	@UiField
	HTML content;

	@UiField
	PushButton btnClose;

	private FloatingTipWidget() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	public static PopupPanel alignTo(UIObject target, String htmlContent) {
		FloatingTipWidget w = new FloatingTipWidget();

		w.content.setHTML(SafeHtmlUtils.fromString(htmlContent));

		final PopupPanel pp = new PopupPanel(false);
		pp.setWidth("230px");
//		pp.getElement().getStyle().setProperty("minWidth", 180.0, Unit.PX);
		pp.setWidget(w);
		w.btnClose.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				pp.hide();
			}
		});

		pp.showRelativeTo(target);

		Align align = getAlign(target, pp);

		switch (align) {
		case BOTTOM_LEFT:
			w.topRight.setResource(CommonResources.INSTANCE.topRightArrow());
			break;
		case BOTTOM_RIGHT:
			w.topLeft.setResource(CommonResources.INSTANCE.topLeftArrow());
			break;
		case TOP_LEFT:
			w.bottomRight.setResource(CommonResources.INSTANCE.bottomRightArrow());
			break;
		case TOP_RIGHT:
			w.topLeft.setResource(CommonResources.INSTANCE.topLeftArrow());
			break;
		}

		return pp;
	}

	private static Align getAlign(UIObject target, PopupPanel pp) {
		int tleft = target.getAbsoluteLeft();
		int ttop = target.getAbsoluteTop();

		int ppleft = pp.getAbsoluteLeft();
		int pptop = pp.getAbsoluteTop();

		if (ppleft >= tleft) {
			if (pptop > ttop) {
				return Align.BOTTOM_RIGHT;
			} else {
				return Align.TOP_RIGHT;
			}
		} else {
			if (pptop > ttop) {
				return Align.BOTTOM_LEFT;
			} else {
				return Align.TOP_LEFT;
			}
		}
	}

}
